<template>
  <div class="orders-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>我的订单</h2>
          <el-select v-model="statusFilter" placeholder="订单状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="待付款" value="pending" />
            <el-option label="已付款" value="paid" />
            <el-option label="已发货" value="shipped" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="filteredOrders"
        style="width: 100%"
      >
        <el-table-column prop="orderId" label="订单编号" width="180" />
        <el-table-column prop="orderDate" label="下单时间" width="180">
          <template #default="{ row }">
            {{ new Date(row.orderDate).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" width="120">
          <template #default="{ row }">
            ¥{{ row.totalAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="商品信息">
          <template #default="{ row }">
            <div v-for="item in row.items" :key="item.productId" class="order-item">
              <span>{{ item.productName }}</span>
              <span class="item-quantity">x{{ item.quantity }}</span>
              <span class="item-price">¥{{ item.price.toFixed(2) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === 'pending'"
              type="primary"
              link
              @click="handlePay(row)"
            >
              付款
            </el-button>
            <el-button
              v-if="row.status === 'pending'"
              type="danger"
              link
              @click="handleCancel(row)"
            >
              取消
            </el-button>
            <el-button
              v-if="row.status === 'shipped'"
              type="success"
              link
              @click="handleConfirm(row)"
            >
              确认收货
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalOrders"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 支付对话框 -->
    <el-dialog
      v-model="payDialogVisible"
      title="订单支付"
      width="400px"
    >
      <div class="pay-dialog-content">
        <p>订单金额：¥{{ selectedOrder?.totalAmount.toFixed(2) }}</p>
        <el-form :model="payForm" label-width="80px">
          <el-form-item label="支付方式">
            <el-radio-group v-model="payForm.method">
              <el-radio label="alipay">支付宝</el-radio>
              <el-radio label="wechat">微信支付</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="payDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPay">
            确认支付
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCustomerStore } from '@/stores/customerStore'

const customerStore = useCustomerStore()
const loading = ref(false)
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const payDialogVisible = ref(false)
const selectedOrder = ref(null)

const payForm = ref({
  method: 'alipay'
})

// 模拟订单数据
const orders = ref([
  {
    orderId: 'ORD20240301001',
    orderDate: '2024-03-01T10:00:00',
    totalAmount: 299.00,
    status: 'pending',
    items: [
      {
        productId: 'P001',
        productName: '新鲜苹果',
        quantity: 2,
        price: 99.00
      },
      {
        productId: 'P002',
        productName: '有机胡萝卜',
        quantity: 1,
        price: 101.00
      }
    ]
  },
  {
    orderId: 'ORD20240228001',
    orderDate: '2024-02-28T15:30:00',
    totalAmount: 199.00,
    status: 'paid',
    items: [
      {
        productId: 'P003',
        productName: '进口牛肉',
        quantity: 1,
        price: 199.00
      }
    ]
  }
])

const filteredOrders = computed(() => {
  let result = orders.value
  if (statusFilter.value) {
    result = result.filter(order => order.status === statusFilter.value)
  }
  return result
})

const totalOrders = computed(() => filteredOrders.value.length)

const getStatusType = (status) => {
  const types = {
    pending: 'warning',
    paid: 'info',
    shipped: 'primary',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    pending: '待付款',
    paid: '已付款',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status] || status
}

const handlePay = (order) => {
  selectedOrder.value = order
  payDialogVisible.value = true
}

const handleCancel = async (order) => {
  try {
    await ElMessageBox.confirm(
      '确定要取消该订单吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 更新订单状态
    const index = orders.value.findIndex(o => o.orderId === order.orderId)
    if (index !== -1) {
      orders.value[index].status = 'cancelled'
      ElMessage.success('订单已取消')
    }
  } catch {
    // 用户取消操作
  }
}

const handleConfirm = async (order) => {
  try {
    await ElMessageBox.confirm(
      '确认已收到商品？',
      '确认收货',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // 更新订单状态
    const index = orders.value.findIndex(o => o.orderId === order.orderId)
    if (index !== -1) {
      orders.value[index].status = 'completed'
      ElMessage.success('已确认收货')
    }
  } catch {
    // 用户取消操作
  }
}

const confirmPay = async () => {
  try {
    // 模拟支付过程
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新订单状态
    const index = orders.value.findIndex(o => o.orderId === selectedOrder.value.orderId)
    if (index !== -1) {
      orders.value[index].status = 'paid'
      ElMessage.success('支付成功')
      payDialogVisible.value = false
    }
  } catch (error) {
    ElMessage.error('支付失败，请重试')
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

onMounted(async () => {
  loading.value = true
  try {
    // 这里可以添加从后端获取订单数据的逻辑
    await new Promise(resolve => setTimeout(resolve, 1000))
  } catch (error) {
    ElMessage.error('获取订单数据失败')
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.orders-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
}

.order-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.order-item:last-child {
  margin-bottom: 0;
}

.item-quantity {
  margin: 0 8px;
  color: #909399;
}

.item-price {
  margin-left: auto;
  color: #f56c6c;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.pay-dialog-content {
  text-align: center;
}

.pay-dialog-content p {
  font-size: 18px;
  color: #f56c6c;
  margin-bottom: 20px;
}
</style> 